var connect = require('connect');
var getRawBody = require('raw-body');
var typer = require('media-typer');
/**
 * [限制数据包的大小]
 * @param  {[type]} options [like {"limit":"2kb"}}]
 * @return {[type]}         [description]
 */
function limit(options) {
    return function(req, res, next) {
        if (req.method.toUpperCase() === 'POST') {
            getRawBody(req, {
                length: req.headers['content-length'],
                limit: options.limit,
                encoding: typer.parse(req.headers['content-type']).parameters.charset
            }, function(err, string) {
                if (err) return next(err);
                req.text = string;
                next();
            });
        } else {
            next();
        }
    }
}

function errorHandler() {
    return function(err, req, res, next) {
        res.statusCode = 500;
        res.setHeader('Content-Type', 'text/plain;charset=UTF-8')
        res.end('数据包太大' + err.stack);
    }
}
module.exports = function(options) {
    return connect().use(limit(options)).use(errorHandler());
}